<script setup>
import { getCurrentInstance, ref } from 'vue';
import { appendRecordMoment, deleteRecordById, getAdminRecords, getRecords } from '@/api/parser.js';
import { downloadByUrl, optimizedFormat } from '@/utils/assets.js';
import { getIsAdmin } from '@/utils/cookie.js';
import { useTableFormatter } from '@/mixins/commonTableFormatter.js';

const instance = getCurrentInstance();
const { $message } = instance.appContext.config.globalProperties;
const { VITE_INTERFACE_DOMAIN } = import.meta.env;

const { timeFormatter, emptyFormatter } = useTableFormatter();

const isAdmin = getIsAdmin();
// 设置表格数据
const tableData = ref([]);
const columns = [
  { prop: 'fileName', label: '文件名称', width: 500 },
  { prop: 'qklw', label: '期刊/学校名称' },
  { prop: 'qklwType', label: '期刊论文类别' },
  { prop: 'status', label: '状态' },
  { prop: 'fileName', label: '操作', slot: true },
  { prop: 'createTime', label: '上传时间', formatter: timeFormatter },
  // { prop: 'comment', label: '备注' },
];
if (isAdmin) {
  columns.splice(1, 0, { prop: 'tplName', label: '模板名称' });
}
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
async function getTableData() {
  const api = isAdmin === 'true' ? getAdminRecords : getRecords;
  const returnData = await api({
    pageSize: pageSize.value,
    pageNum: currentPage.value,
  });
  if (returnData?.code === 200) {
    console.log(returnData);
    tableData.value = returnData.rows;
    total.value = returnData.total;
  }
}
function paginationChange() {
  getTableData();
}
getTableData();
// 预览模版 | 下载模版
async function downLoadTpl(item) {
  console.log(VITE_INTERFACE_DOMAIN);
  const prefix = VITE_INTERFACE_DOMAIN.startsWith('http')
    ? VITE_INTERFACE_DOMAIN
    : `${window.location.origin}${VITE_INTERFACE_DOMAIN}`;
  const fileName = item.fileName.replace('.docx', '');
  const date = optimizedFormat(new Date().getTime(), 'yyyyMMddHHmmss');
  downloadByUrl(`${prefix}/parser/downloadProcessFile?docId=${item.id}`, `${fileName}_${date}`);
}
// 删除模版
async function deleteHandle(item) {
  const returnData = await deleteRecordById({ id: item.id });
  if (returnData?.code === 200) {
    $message.success(returnData?.msg);
    await getTableData();
  } else {
    $message.error(returnData?.msg);
  }
}
// 自定义删除模版
async function customerDelete(item) {
  const returnData = await deleteHandle(item);
  if (returnData) {
    await getTableData();
  }
}
// 修改备注
const showCommentDialog = ref(false); // 修改备注弹窗
const comment = ref(''); // 备注
let setRow = {};
function commentClick(row) {
  if (!showCommentDialog.value) {
    comment.value = row.comment;
    setRow = row;
    showCommentDialog.value = true;
  }
}
async function commentChangeClick() {
  const formData = new FormData();
  formData.append('content', comment.value);
  formData.append('id', setRow.id);
  const returnData = await appendRecordMoment(formData);
  if (returnData?.code === 200) {
    $message.success('修改成功');
    await getTableData();
    showCommentDialog.value = false;
  } else {
    $message.error(returnData?.msg);
  }
}
</script>

<template>
  <el-table :data="tableData" border>
    <template v-for="(item, index) in columns" :key="index">
      <el-table-column
        :prop="item.prop"
        :label="item.label"
        :width="item.width || null"
        :formatter="item.formatter || emptyFormatter"
        show-overflow-tooltip
      >
        <template v-if="item.slot" #default="{ row }">
          <img
            v-if="row.status === '已完成'"
            src="@/assets/images/personalCenter/look-icon.png"
            alt=""
            class="look-icon icon"
            title="预览"
            @click="downLoadTpl(row)"
          />
          <img
            src="@/assets/images/personalCenter/delete-icon.png"
            alt=""
            class="delete-icon icon"
            title="删除"
            @click="customerDelete(row)"
          />
          <img
            v-if="row.status === '未完成'"
            src="@/assets/images/personalCenter/upload-icon.png"
            alt=""
            class="delete-icon icon"
            title="下载"
            @click="downLoadTpl(row)"
          />
        </template>
      </el-table-column>
    </template>
    <el-table-column prop="comment" label="备注">
      <template #default="{ row, column }">
        <span>{{ row.comment || '--' }}</span>
        <br />
        <el-button type="text" @click="commentClick(row)">修改备注</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="global-pagination-box">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @change="paginationChange"
    />
  </div>
  <el-dialog title="修改备注" v-model="showCommentDialog" width="500px">
    <el-input v-model="comment" type="textarea" auto-complete="off" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showCommentDialog = false">取消修改</el-button>
        <el-button type="primary" @click="commentChangeClick"> 修改 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="less">
@import './record.less';
</style>
